package com.dhecp.project.quartz.task;

import com.dhecp.common.config.Global;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.core.utils.qywx.QyWxApiUrls;
import com.dhecp.core.utils.qywx.QyWxResponse;
import com.dhecp.core.utils.qywx.UserEntity;
import com.dhecp.core.utils.qywx.WeChatUtils;
import com.dhecp.project.flowable.domain.ActRuntimeTask;
import com.dhecp.project.flowable.service.ActProcessTaskService;
import com.dhecp.project.system.domain.SysUserInfo;
import com.dhecp.project.system.service.SysModuleNoticeService;
import com.dhecp.project.system.service.SysUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName WeChatTask
 * @Description TODO
 * @Author alula
 * @Date 2022-02-25 15:20
 */
@Component("weChatTask")
public class WeChatTask {

    private static final Logger logger = LoggerFactory.getLogger(WeChatTask.class);

    @Autowired
    private SysModuleNoticeService sysModuleNoticeService;

    @Autowired
    private ActProcessTaskService actProcessTaskService;

    @Autowired
    private SysUserInfoService userInfoService;

    /** 根据类型自动发送任务与通知
     *	定时任务执行
     *	查询已绑定企业微信账号并且尚未发送的未读通知，修改其发送标志并发送应用消息
     * @param type "text"://文本消息 "textcard"://文本卡片消息
     */
    public void sendNoticeAndTask(String type) {
        try {
            if (StringUtils.isEmpty(type)){//当type为空时，默认为text
                type = "text";
            }
            //查询已绑定企业微信账号并且尚未发送的未读通知
            List<Map<String, Object>> noticeList = sysModuleNoticeService.queryModuleNoticeWdWithWeChatId();
            List<String> sendUserList = null;
            String userId = "";
            String id = "";
            List<String> noticeIdList = new ArrayList<>();
            for(Map<String, Object> notice : noticeList) {
                userId = notice.get("enWeChatId").toString();//指定接收消息的成员
                sendUserList = new ArrayList<>();
                if (!StringUtils.isEmpty(userId)) {
                    sendUserList.add(userId);
                }
                Map<String, Object> sendContent = new HashMap<String, Object>();
                String sendText = "【未读通知】";
                sendText += "\n主题：" + (notice.get("taskContent") == null?"":notice.get("taskContent").toString());
                sendText += "\n摘要：" + (notice.get("taskAbstract") == null?"":notice.get("taskAbstract").toString());
                sendText += "\n用户编号：" + (notice.get("cUser") == null?"":notice.get("cUser").toString());
                sendText += "\n通知用户：" + (notice.get("cUserName") == null?"":notice.get("cUserName").toString());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                sendText += "\n创建时间：" + (notice.get("createTime") == null?"":sdf.format(notice.get("createTime")));
                sendText += "\n处理期限：" + (notice.get("limitTime") == null?"":sdf.format(notice.get("limitTime")));
                id = notice.get("guid").toString();
                QyWxResponse qyWxResponse = WeChatUtils.sendTextMsg(sendUserList, null,null, sendText);
                if (qyWxResponse.getErrCode() == 0) {
                    noticeIdList.add(id);
                }else{
                    logger.error("【企业微信】定时自动发送通知ID为["+id+"]出错，错误信息为：" + qyWxResponse.getErrMsg());
                }
                Thread.sleep(500);
            }
            //批量更新通知已发标记
            if (noticeIdList != null && noticeIdList.size() > 0){
                sysModuleNoticeService.updateNoticeWxSendFlag(noticeIdList);
            }
            //查询已绑定企业微信账号并且尚未发送的待办任务，且在线用户最后访问时间大于三分钟
            List<Map<String, Object>> userList = actProcessTaskService.queryUserWithWeChatId();
            for(Map<String, Object> user : userList) {
                Map<String, Object> queryParams = new HashMap<String, Object>();
                queryParams.put("assignee", user.get("userId").toString());//指定接收消息的成员
                queryParams.put("filterWx", "1");//过滤制单状态且已推送企业微信消息的任务
                queryParams.put("filterEcpTask", "1");//过滤不发送的任务功能
                List<ActRuntimeTask> taskList = actProcessTaskService.queryTodoActRuntimeTask(queryParams);
                List<String> taskIdList = new ArrayList<>();
                for(ActRuntimeTask task : taskList) {
                    userId = user.get("enWeChatId").toString();//指定接收消息的成员
                    sendUserList = new ArrayList<>();
                    if (!StringUtils.isEmpty(userId)) {
                        sendUserList.add(userId);
                    }
                    String sendTitle = "";
                    String sendText = "用户编号：" + user.get("userId").toString();
                    sendText += "\n任务名称：" + (task.getName() == null?"":task.getName());
                    sendText += "\n所属公司：" + (task.getCorpName() == null?"":task.getCorpName());
                    sendText += "\n发起人：" + (task.getOrganizerName() == null?"":task.getOrganizerName());
                    sendText += "\n优先级：" + (task.getPriority() == 1 ? "一般" : task.getPriority() == 2 ? "重要" : task.getPriority() == 3 ? "紧急" : "");
                    sendText += "\n上环节意见：" + (task.getActComment() == null?"":task.getActComment());//防止为null
                    sendText += "\n流程摘要：" + (task.getProcessRemark() == null?"":task.getProcessRemark());//防止为null
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    sendText += "\n创建时间：" + (task.getCreateTime() == null?"":sdf.format(task.getCreateTime()));
                    id = task.getId().toString();
                    QyWxResponse qyWxResponse = new QyWxResponse();
                    switch(type) {
                        case "text"://文本消息
                            sendTitle = "【待办任务】\n" + task.getProcessTitle() + "\n";
                            sendText = sendTitle + sendText;
                            qyWxResponse = WeChatUtils.sendTextMsg(sendUserList, null,null, sendText);
                            break;
                        case "textcard"://文本卡片消息
                            sendTitle = "【待办任务】\n【" + task.getProcessTitle() + "】";
                            String sendUrl = QyWxApiUrls.OAUTH2_AUTHORIZE_URL.replace("APPID", WeChatUtils.APPID).replace("REDIRECT_URI", URLEncoder.encode(Global.getH5DeployUrl() + "?navTo=task&taskId=" + id));
                            qyWxResponse = WeChatUtils.sendActionCardMsg(sendUserList, null,null, sendTitle, sendText, sendUrl, "跳转审批");
                            break;
                    }
                    if (qyWxResponse.getErrCode() == 0) {
                        taskIdList.add(id);
                    }else{
                        logger.error("【企业微信】定时自动发送待办任务ID为["+id+"]出错，错误信息为：" + qyWxResponse.getErrMsg());
                    }
                    Thread.sleep(500);
                }
                //批量更新任务已发标记，以一个用户为单位
                if (taskIdList !=  null && taskIdList.size() > 0){
                    actProcessTaskService.updateTaskWxSendFlag(taskIdList);
                }
            }
        } catch (Exception ex) {
            logger.error("【企业微信】定时自动发送微信消息出错，错误信息为：" + ex.getMessage());
        }
    }

    /**
     * 每天晚上同步用户到钉钉
     */
    public void syncUserInfo() {
        try {
            Map<String, Object> deleteParams = new HashMap<>();
            UserEntity userModel = null;
            Map<String, Object> queryParams = new HashMap<>();
            List<SysUserInfo> userList = userInfoService.queryUserListBySync(queryParams);
            for (SysUserInfo  userInfo:userList) {
                if (userInfo.getUserId().equals("admin")){//admin用户不同步
                    continue;
                }
                if (StringUtils.isEmpty(userInfo.getSyncUnionId())){//未同步
                    if(userInfo.getDisabled() == false){//且未禁用，创建新增同步
                        userModel = new UserEntity();
                        userModel.setUserId(userInfo.getUserId());
                        userModel.setUserName(userInfo.getUserName());
                        userModel.setMobile(userInfo.getUserPhone2());
                        userModel.setTelephone(userInfo.getUserPhone1());
                        List<Integer> department = new ArrayList<>();
                        department.add(1);
                        userModel.setDepartment(department);
                        userModel.setPosition(userInfo.getPositionNameDa());
                        userModel.setGender((userInfo.getUserSex().equals("女") ? "0":"1"));
                        userModel.setEmail(userInfo.getUserEmail());
                        //userModel.setBizMail(userInfo.getUserEmail());
                        userModel.setDirectLeader(userInfo.getUserLeader());
                        userModel.setAddress(userInfo.getUserAddress());
                        userModel.setEnable(1);
                        userModel.setToInvite(true);
                        QyWxResponse qyWxResponse = WeChatUtils.userCreate(userModel);
                        if (qyWxResponse.getErrCode() == 0){
                            userInfoService.updateUserBySyncUnionId(userInfo.getUserId(), userInfo.getUserId(), "");
                        }else{
                            logger.error("【企业微信】定时同步创建用户[" + userInfo.getUserId() + "]出错，具体错误为：" + qyWxResponse.getErrMsg());
                        }
                    }
                }else{
                    if (userInfo.getDisabled() == false){//已同步，且未禁用，更新同步
                        userModel = new UserEntity();
                        userModel.setUserId(userInfo.getUserId());
                        userModel.setUserName(userInfo.getUserName());
                        userModel.setMobile(userInfo.getUserPhone2());
                        userModel.setTelephone(userInfo.getUserPhone1());
                        List<Integer> department = new ArrayList<>();
                        department.add(1);
                        userModel.setDepartment(department);
                        userModel.setPosition(userInfo.getPositionNameDa());
                        userModel.setGender((userInfo.getUserSex().equals("女") ? "0":"1"));
                        userModel.setEmail(userInfo.getUserEmail());
                        //userModel.setBizMail(userInfo.getUserEmail());
                        userModel.setDirectLeader(userInfo.getUserLeader());
                        userModel.setAddress(userInfo.getUserAddress());
                        userModel.setEnable(1);
                        userModel.setToInvite(true);
                        QyWxResponse qyWxResponse = WeChatUtils.userUpdate(userModel);
                        if (qyWxResponse.getErrCode() != 0){
                            logger.error("【企业微信】定时同步更新用户[" + userInfo.getUserId() + "]出错，具体错误为：" + qyWxResponse.getErrMsg());
                        }
                    }else{//已同步，禁用，删除同步
                        QyWxResponse qyWxResponse = WeChatUtils.userDelete(userInfo.getUserId());
                        if (qyWxResponse.getErrCode() == 0) {
                            userInfoService.updateUserBySyncUnionId(userInfo.getUserId(), "", "");//删除同步用户后，把原来同步的ID清空
                        }
                        else{
                            logger.error("【企业微信】定时同步删除用户[" + userInfo.getUserId() + "]出错，具体错误为：" + qyWxResponse.getErrMsg());
                        }
                    }
                }
            }
        } catch (Exception ex) {
            logger.error("【企业微信】定时同步用户到企业微信出错，错误信息为：" + ex.getMessage());
        }
    }
}
